﻿namespace DotNetHackathon.GBA.ApiCommon.ExceptionHandling
{
    public class DefaultExceptionToErrorResultConverter: IExceptionToErrorResultConverter
    {
        public ErrorResult Convert(Exception exception)
        {
            var errorInfo = CreateErrorInfoWithoutCode(exception);

            if (exception is IHasErrorCode hasErrorCodeException)
            {
                errorInfo.Code = hasErrorCodeException.Code;
            }

            return errorInfo;
        }

        protected virtual ErrorResult CreateErrorInfoWithoutCode(Exception exception)
        {
            exception = TryToGetActualException(exception);

            var errorResult = new ErrorResult
            {
                Message = exception.Message
            };

            return errorResult;
        }

        protected virtual Exception TryToGetActualException(Exception exception)
        {
            if (exception is AggregateException && exception.InnerException != null)
            {
                var aggException = exception as AggregateException;

                if (aggException?.InnerException is BusinessException)
                {
                    return aggException.InnerException;
                }
            }

            return exception;
        }
    }
}
